package com.lzw.breezeNovel.common.utils;


import com.lzw.breezeNovel.common.exception.BaseException;
import com.lzw.breezeNovel.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.common.utils
 * @date 2025/2/27
 * @description Minio配置类
 */
@SuppressWarnings("all")
public class JwtUtil {
    //token有效期
    private static long tokenExpiration = 60 * 60 * 10000L;

    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    /**
     * 解析token获取用户信息
     * @param userId
     * @param username
     * @return
     */
    public static String createToken(String phone, String username) {
              String token = Jwts.builder().
                      setSubject("Login_INFO").
                      setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                      claim("phone", phone).
                      claim("username", username).
                      signWith(tokenSignKey, SignatureAlgorithm.HS256).
                      compact();
              return token;
          }

    /**
     * 校验token是否有效
     * @param token
     */
    public static Claims parseToken(String token)
          {
             try {
                 JwtParser build = Jwts.parserBuilder().setSigningKey(tokenSignKey).build();
                 Jws<Claims> claimsJws = build.parseClaimsJws(token);
                 Claims body = claimsJws.getBody();
                 return body;
             }catch (ExpiredJwtException e)
             {
                 throw new BaseException(ResultCodeEnum.TOKEN_EXPIRED);
             }catch (JwtException e)
             {
                 throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
             }
          }


}